package com.sherlocky.document.config;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个性化 MVC 配置
 * @author: zhangcx
 * @date: 2019/8/8 13:35
 */
@Configuration
public class DocumentApiMvcConfiguration implements WebMvcConfigurer {
    @Resource(name="thymeleafViewResolver")
    private ThymeleafViewResolver thymeleafViewResolver;
    @Value("${onlyoffice.document-server.host}")
    private String documentServerHost;
    @Value("${onlyoffice.document-server.api.js}")
    private String documentServerApiJs;


/*    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // view 相关配置在 application.properties 中，使用
        registry.addViewController("/").setViewName("/search");
    }*/

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        if (thymeleafViewResolver != null) {
            Map<String, Object> vars = new HashMap<>(8);
            vars.put("documentServerApiJs", String.format(documentServerApiJs, documentServerHost));
            // 静态参数，只取一次值
            thymeleafViewResolver.setStaticVariables(vars);
        }
    }

    /**
     * 替换springboot默认的json转换器为 Fastjson
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // fastjson 消息转换对象
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        /**
         * 自定义配置...如编码字符集，日期格式等
         */
        FastJsonConfig config = new FastJsonConfig();
        config.setCharset(Charsets.UTF_8);
        converter.setFastJsonConfig(config);

        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(list);

        /**
         * 添加到 converters
         * 如果是直接添加，会排在默认的 MappingJackson 转换器后面，导致fastjson失效。
         * 方法1.可以遍历转换器列表，替换 MappingJackson 为 fastjson转换器
         * 方法2.或者直接在转换器列表首部加入fastjson转换器？（未验证）
         */
        // converters.add(0, converter);
        for (int i = 0; i < converters.size(); i++) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.set(i, converter);
            }
        }
    }
}
